import requests
from time import sleep
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from api_test.api.base_api import BaseApi
from utils.configurator import config
from utils.data_loader import DataLoader


class FeiShuApi(BaseApi):
    """
    飞书的api公共特性， 获取token，获取身份信息
    """
    def __init__(self):
        super().__init__()
        app_id = config["account"]["app_id"]
        app_secret = config["account"]["app_secret"]
        self.session.headers["Content-Type"] = "application/json; charset=utf-8"
        access_token = self.get_access_token(app_id, app_secret)
        if access_token:
            self.session.headers["Authorization"] = "Bearer " + access_token
        else:
            raise Exception("Failed to get authentication token!")

    def get_access_token(self, app_id, app_secret):
        """获取token"""
        path = "/open-apis/auth/v3/tenant_access_token/internal"
        data = {
            "app_id": app_id,
            "app_secret": app_secret
        }
        self.session.headers["Content-Type"] = "application/json; charset=utf-8"
        # disable InsecureRequestWarning
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
        response = self.send_request("POST", self.base_url + path, json=data)
        if response.status_code == 200:
            access_token = response.json().get("tenant_access_token")
            # DataLoader.write_date(access_token)
            print(f"token:{access_token}")
            return access_token
        else:
            return None

if __name__ == '__main__':
    feishu = FeiShuApi()

